#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import log
import json
from controls import data_product_img_mysql
from controls import data_img_base_mysql
from utils import fdfs
from utils import file_util
from utils.util import get_utf8_str

'''
仅供后台使用，更新城市特产所有图片数据
调用方式：参数1数据文件名, 参数2为该城市所有特产图片存放文件夹(里面按pid作为子文件夹, 里面按数字顺序放置图片)
python import_product_imgs_data.pyc city1.json img_fold
'''
def import_product_imgs(datafile, img_path):

    if not (img_path and datafile) :
        print 'please input jsonfile and img_path'
    print 'datafile : %s' % datafile
    print 'img_path : %s' % img_path

    insert = 1 # insert operate
    update = 2 # update operate
    delete = 3 # delete operate
    print 'op_type----------insert: %d, update: %d, delete: %d' % (insert, update, delete)

    # read all json file content
    jsonfile = open( datafile, 'r' )
    json_dict = {}
    try:
        all_the_text = jsonfile.read( )
        json_dict = json.loads(get_utf8_str(all_the_text))
    finally:
        jsonfile.close( )

    # data check
    if not json_dict :
        print 'jsonfile is empty.'
        sys.exit()
    if 'cityid' not in json_dict :
        print 'jsonfile dont has cityid.'
        sys.exit()
    if not os.path.exists( img_path ) :
        print 'img_path dont existed : ' + img_path
        sys.exit()

    if not img_path.endswith('/') :
        img_path += '/'
    cityid = int( json_dict['cityid'] )
    del json_dict['cityid']

    for ( pid, imgs_dict ) in json_dict.items() :
        productid = int(pid)
        print "productid:"+ str(productid) +",imgs:"+str(imgs_dict)

        '''jsonfile content:
        { "1" : {
            "0" : {"imgname" : "0.png", "op_type" : 2 },
            "1" : {"imgname" : "1.png", "op_type" : 2 },
            "2" : {"imgname" : "2.png", "op_type" : 2 },
            "3" : {"imgname" : "3.png", "op_type" : 2 }
            },
          "2" : {
            "0" : {"imgname" : "0.png", "op_type" : 2 },
            "1" : {"imgname" : "1.png", "op_type" : 2 },
            "2" : {"imgname" : "2.png", "op_type" : 2 },
            "3" : {"imgname" : "3.png", "op_type" : 2 }
            },
          "cityid" : 1
        }
        '''
        if not imgs_dict :
            continue

        for ( num_str, img_item ) in imgs_dict.items() :

            num = int (num_str)
            type = img_item['op_type']
            img_item['pid'] = productid
            img_item['num'] = num

            data_product_img_mysql.create_product_img_table_if_not_exist(cityid)
            filepath = os.path.join( img_path, str(productid) )
            print filepath
            if insert == type :
                print 'insert into product_img_%d, productid=%d, num=%d, filename=%s' % (cityid, productid, num, img_item['imgname'])
                if not img_item['imgname'] :
                    continue
                res = file_util.img_file_upload_by_filename_v2(filepath, img_item['imgname'])
                print res
                if res['ret'] == 0 and res['res']:
                    img_item['imgid']=res['res']['imgid']
                    data_product_img_mysql.add_product_img_item(cityid, img_item)

            if update == type :
                print 'update product_img_%d, productid=%d, num=%d, filename=%s' % (cityid, productid, num, img_item['imgname'])
                if not img_item['imgname'] :
                    continue

                res = file_util.img_file_upload_by_filename_v2(filepath, img_item['imgname'])
                print res
                if res['ret'] == 0 and res['res']:
                    # delete old img in fdfs
                    img_dict = data_product_img_mysql.get_product_img_by_pid_num( cityid, productid, num )
                    if not img_dict :
                        img_item['imgid']=res['res']['imgid']
                        data_product_img_mysql.add_product_img_item(cityid, img_item)
                        continue
                    else :
                        # delete old img in fdfs
                        imgid = img_dict['imgid']
                        img_base_item = data_img_base_mysql.get_img_base_by_imgid( imgid )

                        p_group = str(img_base_item['group'])
                        file_id = img_base_item['path'] + '.'+ img_base_item['ext']
                        file_id_100 = img_base_item['path'] + '_100' + '.'+ img_base_item['ext']
                        file_id_300 = img_base_item['path'] + '_300' + '.'+ img_base_item['ext']

                        print 'group=%s, file_id=%s' % (p_group, file_id)
                        try :
                            fdfs.delete_file_by_group_file_id( p_group, file_id )
                            fdfs.delete_file_by_group_file_id( p_group, file_id_100 )
                            fdfs.delete_file_by_group_file_id( p_group, file_id_300 )
                        except Exception as e :
                            log.exp(e)
                        data_img_base_mysql.delete_img_base_by_imgid(imgid)

                        # update new img in product_img table
                        img_item['imgid']=res['res']['imgid']
                        data_product_img_mysql.update_product_img_item( cityid, img_item )
            if delete == type :
                print 'delete from product_img_%d, productid=%d, num=%d, filename=%s' % (cityid, productid, num, img_item['imgname'])
                # delete old img in fdfs
                img_dict = data_product_img_mysql.get_product_img_by_pid_num( cityid, productid, num )
                if img_dict :
                    # delete old img in fdfs
                    imgid = img_dict['imgid']
                    img_base_item = data_img_base_mysql.get_img_base_by_imgid( imgid )

                    p_group = str(img_base_item['group'])
                    file_id = img_base_item['path'] + '.'+ img_base_item['ext']
                    file_id_100 = img_base_item['path'] + '_100' + '.'+ img_base_item['ext']
                    file_id_300 = img_base_item['path'] + '_300' + '.'+ img_base_item['ext']
                    try :
                        fdfs.delete_file_by_group_file_id( p_group, file_id )
                        fdfs.delete_file_by_group_file_id( p_group, file_id_100 )
                        fdfs.delete_file_by_group_file_id( p_group, file_id_300 )
                    except Exception as e :
                        log.exp(e)
                    data_img_base_mysql.delete_img_base_by_imgid(imgid)

                    # delete img in product_img table
                    data_product_img_mysql.delete_product_img_item( cityid, img_item)

    return True

if __name__ == '__main__':
    datafile1 = sys.argv[1]
    img_path1 = sys.argv[2]
    import_product_imgs(datafile1, img_path1)
    print 'OK'

